<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\models\Tag;
class TriangularContentRelation extends DataType {
	public static $name = 'Triangular Content Relation';
	public static $fields = array();
	
	public static function validate($field, $data, $results) {
		$relation = getFieldMetaData($field->cf_id, 'relation');
		if($field->cf_required && !$data['relations_'.$field->cf_id]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		else {
			$results['db_fields']['relations'][$relation] = $data['relations_'.$field->cf_id];
		}
		
		return $results;
	}
	
	public static function formHeader($field) {
		Modulator()->includeScript('jquery');
		Modulator()->includeScript(getCommonFile('concerto/javascript/content-relation.js'));
		?>
		<script type="text/javascript">
			$(document).ready(function() {
				$('#relations_<?=$field->cf_id?>').triangularContentRelation();
			});
		</script>
		<?php
	}
	
	public static function display($formElements) {
			?>
			
			<fieldset class="relation-field" id="<?=$formElements['elements']['id']?>">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<div class="two-column">
			<?php echo $formElements['elements']['secondary_select'];?>
			<?php echo $formElements['elements']['tertiary_select'];?>
			</div>
			<div class="two-column">
				<label>Relations</label>
				<?php echo $formElements['elements']['relation_list'];?>
			</div>
			<div style="clear:both;"></div>
			</section>
			</fieldset>
			<?php
	}
	
	public static function build($field, $data) {
		
		// Get field meta data
		$relation = getFieldMetaData($field->cf_id, 'relation');
		//$display = getFieldMetaData($field->cf_id, 'display');
		
		// Get preexisting relations
		$contentId = $data['content_id'];
		
		
		
		/** Display relations */
		$formElements = array('column'=>'relation_'.$relation, 'display'=>$field->cf_display_name, 'data_type'=>'ContentRelation', 'elements'=>array());
	
		$existingRelations = $data['relations_'.$field->cf_id];
		// Get available content for this relation
		$row = DB()->getRow("SELECT * FROM `cn_content_relation_types` WHERE `crt_id`='$relation'");
		if($row->crt_type1 == $field->cf_content_type) {
			$secondaryType = $row->crt_type2;
			$tertiaryType = $row->crt_type3;
		}
		elseif($row->crt_type2 == $field->cf_content_type) {
			$secondaryType = $row->crt_type1;
			$tertiaryType = $row->crt_type3;
		}
		else {
			$secondaryType = $row->crt_type1;
			$tertiaryType = $row->crt_type2;
		}
		
		$relationList = '<ul class="triangular-relation-list">';
		foreach($existingRelations as $id=>$existing) {
			$relationList .= '<li>';
			$relationList .= '<input type="hidden" name="relations_'.$field->cf_id.'['.$id.']['.$secondaryType.']" value="'.$existing[$secondaryType].'"/>';
			$relationList .= '<input type="hidden" name="relations_'.$field->cf_id.'['.$id.']['.$tertiaryType.']" value="'.$existing[$tertiaryType].'"/>';
			$relationList .= '<span class="relation-content">'.DB()->getVar("SELECT `content_title` FROM `cn_content` WHERE `content_id`='".$existing[$secondaryType]."'").'</span>';
			$relationList .= ' :: ';
			$relationList .= '<span class="relation-content">'.DB()->getVar("SELECT `content_title` FROM `cn_content` WHERE `content_id`='".$existing[$tertiaryType]."'").'</span>';
			$relationList .= '<a href="javascript:void();" class="remove-multiselect">X</a>';
			$relationList .= '</li>';
		}
		
		$relationList .= '</ul>';
		
		$formElements['elements']['relation_list'] = $relationList;
		
		$attachableSecondaries = DB()->getResults("SELECT * FROM `cn_content` WHERE `content_type`='$secondaryType' ORDER BY `content_title`");
		$secondarySelect = '<label>'.DB()->getVar("SELECT `ct_title` FROM `cn_content_types` WHERE `ct_id`='$secondaryType'").'</label><select data-content-type="'.$secondaryType.'" class="content-relation" name="relations_'.$field->cf_id.'_secondaries[]" id="relations_'.$field->cf_id.'_secondaries">';
		
		$attachableTertiaries = DB()->getResults("SELECT * FROM `cn_content` WHERE `content_type`='$tertiaryType' ORDER BY `content_title`");
		$tertiarySelect = '<label>'.DB()->getVar("SELECT `ct_title` FROM `cn_content_types` WHERE `ct_id`='$tertiaryType'").'</label><select data-content-type="'.$tertiaryType.'" class="content-relation" name="relations_'.$field->cf_id.'_tertiaries[]" id="relations_'.$field->cf_id.'_tertiaries">';
		
		foreach($attachableSecondaries as $content) {
			$secondarySelect .= '<option value="'.$content->content_id.'">'.$content->content_title.'</option>';
		}
		
		$secondarySelect .= '</select>';
		$formElements['elements']['secondary_select'] = $secondarySelect;
		
		foreach($attachableTertiaries as $content) {
			$tertiarySelect .= '<option value="'.$content->content_id.'">'.$content->content_title.'</option>';
		}
		
		$tertiarySelect .= '</select>';
		$formElements['elements']['tertiary_select'] = $tertiarySelect;
		
		$formElements['elements']['id'] = 'relations_'.$field->cf_id;
		
		
		return $formElements;
	
	}
	
	public static function save() {
		$field = $_REQUEST['field'];
		$meta = $_REQUEST['meta_relation'];
		$count = DB()->getCount("SELECT * FROM `cn_field_meta` WHERE `cfm_key`='relation' AND `cfm_field`='$field'");
		if(!$count) {
			$insert = array('cfm_key'=>'relation', 'cfm_value'=>$meta, 'cfm_field'=>$field);
			DB()->insert('cn_field_meta', $insert);
		}
		else {	
			DB()->query("UPDATE `cn_field_meta` SET `cfm_value`='$meta' WHERE `cfm_key`='relation' AND `cfm_field`='$field'");
		}
	}
	
	public static function endForm($field, $data, $id, $type) {
		$relationID = getFieldMetaData($field->cf_id, 'relation');
		$relations = $data['relations'][$relationID];
		if(!$relations) $relations = array();
		
		$formRelations = array();
		$formRelationsImplode = array();
		
		// Get available content for this relation
		$row = DB()->getRow("SELECT * FROM `cn_content_relation_types` WHERE `crt_id`='$relationID'");
		if($row->crt_type1 == $field->cf_content_type) {
			$secondaryType = $row->crt_type2;
			$tertiaryType = $row->crt_type3;
		}
		elseif($row->crt_type2 == $field->cf_content_type) {
			$secondaryType = $row->crt_type1;
			$tertiaryType = $row->crt_type3;
		}
		else {
			$secondaryType = $row->crt_type1;
			$tertiaryType = $row->crt_type2;
		}
		
		foreach($relations as $array) {
			$formRelations[] = array($id, $array[$secondaryType], $array[$tertiaryType]);
		}
		
		
		
		
		$currentRelations = DB()->getResults("SELECT `cn_content_content_relations`.*, `a`.`content_id` AS `content1_id`, `b`.`content_id` AS `content2_id`, `c`.`content_id` AS `content3_id` FROM `cn_content_content_relations` INNER JOIN `cn_content` `a` ON `a`.`content_id`=`ccr_content1` INNER JOIN `cn_content` `b` ON `b`.`content_id`=`ccr_content2` INNER JOIN `cn_content` `c` ON `c`.`content_id`=`ccr_content3` WHERE `ccr_relation`='$relationID' AND (`ccr_content1`='$id' OR `ccr_content2`='$id' OR `ccr_content3`='$id')");
		
		// Get relations
		$existingRelations = array();
		
				$existingRelationsImplode = array();
		foreach($currentRelations as $existing) {
			$existingRelations[$existing->ccr_id] = array($existing->content1_id, $existing->content2_id, $existing->content3_id);
		}
		
				
		foreach($existingRelations as $ccrId=>$array) {
			asort($array);
			$existingRelationsImplode[$ccrId] = implode(',', $array);
		}
		foreach($formRelations as $array) {
			asort($array);
			$formRelationsImplode[] = implode(',', $array);
		}	
		
		// Get relations that we don't have to add
		$noNeed = array_intersect($formRelationsImplode, $existingRelationsImplode);

		// Get relations we need to remove
		$toDelete = array_keys(array_diff($existingRelationsImplode, $noNeed));

		$toDelete = "'".implode("', '", $toDelete)."'";
		
		// Get tags we need to add
		$toAdd = array_diff($formRelationsImplode, $existingRelationsImplode);


		
		DB()->query("DELETE FROM `cn_content_content_relations` WHERE `ccr_id` IN ($toDelete) AND (`ccr_content1`='$id' OR `ccr_content2`='$id' OR `ccr_content3`='$id')");
		foreach($toAdd as $add) {
			$add = explode(',', $add);
			DB()->insert('cn_content_content_relations', array('ccr_content1'=>$add[0], 'ccr_content2'=>$add[1], 'ccr_content3'=>$add[2], 'ccr_relation'=>$relationID));
		}
	}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		$contentId = $data['content_id'];
		$relation = getFieldMetaData($field->cf_id, 'relation');
		$relations = DB()->getResults("SELECT `cn_content_content_relations`.*, `a`.`content_title` AS `content1`, `a`.`content_id` AS `content1_id`, `a`.`content_type` AS `content1_type`, `b`.`content_title` AS `content2`, `b`.`content_id` AS `content2_id`, `b`.`content_type` AS `content2_type`, `c`.`content_title` AS `content3`, `c`.`content_id` AS `content3_id`, `c`.`content_type` AS `content3_type` FROM `cn_content_content_relations` INNER JOIN `cn_content` `a` ON `a`.`content_id`=`ccr_content1` INNER JOIN `cn_content` `b` ON `b`.`content_id`=`ccr_content2` INNER JOIN `cn_content` `c` ON `c`.`content_id`=`ccr_content3` WHERE `ccr_relation`='$relation' AND (`ccr_content1`='$contentId' OR `ccr_content2`='$contentId' OR `ccr_content3`='$contentId')");
		
		// Get relations
		$existingRelations = array();
		foreach($relations as $existing) {
			if($existing->content1_id == $contentId) {
				$existingRelations[$existing->ccr_id] = array($existing->content2_type=>$existing->content2_id, $existing->content3_type=>$existing->content3_id);
			}
			elseif($existing->content2_id == $contentId) {
				$existingRelations[$existing->ccr_id] = array($existing->content1_type=>$existing->content1_id, $existing->content3_type=>$existing->content3_id);
			}
			else {
				$existingRelations[$existing->ccr_id] = array($existing->content1_type=>$existing->content1_id, $existing->content2_type=>$existing->content2_id);
			}
		}
		return array('relations_'.$field->cf_id => $existingRelations);
	}
	
	public static function editForm($field) {
		?>
			<input type="hidden" name="field_id" value="<?=$field->getId()?>"/>
			<ul class="form-fields">
			<li>
			<label>Field Display Name</label>
			<input type="text" name="field_display_name" class="big wide" value="<?=$field->getDisplayName()?>"/>
			</li>
			<li>
			<label>Field Description</label>
			<textarea name="field_description" class="wide"><?=$field->getDescription()?></textarea>
			</li>
			<li>
				<label>Relation</label>
				<select name="meta_relation">
					<?php $relations = DB()->getResults("SELECT * FROM `cn_content_relation_types` WHERE (`crt_type1`='".$field->getContentType()."' OR `crt_type2`='".$field->getContentType()."' OR `crt_type3`='".$field->getContentType()."') AND `crt_relation_type` = 'three-way'");
					foreach($relations as $relation) : ?>
					<option <?= ($field->getMeta('relation') == $relation->crt_id) ? 'selected="selected"' : ''?> value="<?=$relation->crt_id?>"><?=$relation->crt_name?></option>
					<?php endforeach;?>
				</select>
			</li>
			</ul>
			<?php
	}	
	
	public static function prepareData($field, $data, $params) {
		$relations = $data['relations_'.$field->cf_id];
		$contentTypeNames = DB()->getVarArray("SELECT `ct_title` FROM `cn_content_types` ORDER BY `ct_id`");
		$contentTypeIds = DB()->getVarArray("SELECT `ct_id` FROM `cn_content_types` ORDER BY `ct_id`");
		$contentTypes = array_combine($contentTypeIds, $contentTypeNames);
		
		$output = array();
		foreach($relations as $relation) {
			$currentOutput = array();
			foreach($relation as $type=>$id) {
				$currentOutput[$contentTypes[$type]] = new \application\models\Content('id='.$id);
			}
			$output[] = $currentOutput;
		}
		
		return $output;
	}
	
}
?>